package de.grosjohann.android.feuerwehr.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;
import android.util.Log;

public final class FileUtil {

  private static final String NAME = "FileUtil";

  public static void writeFile(Context ctx, String fileName, String data2write) throws IOException {
    FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos));
    bw.write(data2write);
    bw.close();
  }

  public static String readFile(Context ctx, String fileName) {
    String buffer = "";
    try {
      FileInputStream fis = ctx.openFileInput(fileName);
      BufferedInputStream bis = new BufferedInputStream(fis);

      BufferedReader br = new BufferedReader(new InputStreamReader(bis));
      buffer = br.readLine();
      br.close();
    } catch (IOException ex) {
      Log.e(NAME, ex.getMessage(), ex);
    }
    return buffer;
  }

  public static boolean deleteFile(Context ctx, String fileName) {
    return ctx.deleteFile(fileName);
  }

  public static boolean isFileAvailable(Context ctx, String fileName) {
    return readFile(ctx, fileName).length() > 0;
  }
}